<?php

$di = \application\units\Di::getInstance();

$params = [
    'admin_id' => $di->auth->id,
];

['where' => $where, 'bindValue' => $bindValue, 'limit' => $limit, 'order' => $order] = $di->businessCommonQuery->build();

$adminIds    = [];
$authRoleIds = [];
$roleIds     = [];
if ($params['admin_id']) {
    $roleIds     = $di->auth->getChildrenRoleIds($params['admin_id'], true);
    $adminIds    = $di->auth->getChildrenAdminIdsByRoleIds($roleIds, $params['admin_id'], true);
    $authRoleIds = $di->auth->getRoleIdsByAdminId($params['admin_id']);
}

$where                 .= ' and a.id in (:admin_id)';
$bindValue['admin_id'] = $adminIds;

$total = $di->db->find(sprintf('select count(distinct a.id) total from admin a
                                       left join admin_role_access agc on agc.admin_id=a.id
                                       where 1=1 %s', $where), $bindValue)['total'];

$rows = $di->db->query(sprintf('select a.* from admin a
                                        left join admin_role_access agc on agc.admin_id=a.id
                                        where 1=1 %s
                                        group by a.id
                                        %s %s', $where, $order, $limit), $bindValue);


if ($rows) {
    $adminIds = array_column($rows, 'id');
    $roleMap  = $di->db->query('select a.admin_id,a.admin_id,g.* from admin_role_access a
            join admin_role g on g.id=a.role_id
            where admin_id in (:admin_id) and g.id in (:role_ids)', [
        'admin_id' => $adminIds,
        'role_ids' => $roleIds,
    ], PDO::FETCH_ASSOC | PDO::FETCH_GROUP);
    
    foreach ($rows as &$row) {
        unset($row['password'], $row['salt'], $row['token']);
        $row['role_id']   = '';
        $row['role_text'] = '';
        if (isset($roleMap[$row['id']])) {
            $row['role_id']   = implode(',', array_column($roleMap[$row['id']], 'id'));
            $row['role_text'] = implode(',', array_column($roleMap[$row['id']], 'name'));
        }
        
        // 不能操作自己拥有的权限
        if (array_intersect(explode(',', $row['role_id']), $authRoleIds)) {
            $row['disabled'] = 1;
        } else {
            $row['disabled'] = 0;
        }
    }
}

return [
    'total' => $total,
    'rows'  => $rows,
];